package com.aierjun.camera.record;

import android.app.Activity;
import android.hardware.Camera;
import android.media.CamcorderProfile;
import android.media.MediaRecorder;
import android.util.Log;
import android.widget.Toast;

import com.aierjun.camera.widget.RecordCameraView;

import java.io.File;
import java.io.IOException;

/**
 * -----------------------------------
 * (☆^ー^☆)
 *
 * @author : Ani_aierJun
 * github: https://github.com/aierjun
 * email: aierjun@qq.com
 * create in : 13:44 2018/8/7
 * -----------------------------------
 */


public class MediaRecordConfig {

    private MediaRecorder mediaRecorder;
    private Camera mCamera;
    private String mVideoPath;

    private static MediaRecordConfig self;

    public static MediaRecordConfig getInstance() {
        if (self == null)
            self = new MediaRecordConfig();
        return self;
    }

    /**
     * 录制　MediaRecorder 参数配置
     */
    public MediaRecordConfig mediaRecorderSet(RecordCameraView cameraView, String videoPath, MediaRecorder.OnErrorListener onErrorListener) {
        mCamera = cameraView.getCamera();
        mVideoPath = videoPath;
        if (mediaRecorder == null) {
            mediaRecorder = new MediaRecorder();
            mediaRecorder.setOnErrorListener(onErrorListener);
        } else
            mediaRecorder.reset();
        // Step 1: Unlock and set camera to MediaRecorder
        mCamera.unlock();
        mediaRecorder.setCamera(mCamera);
        mediaRecorder.setPreviewDisplay(cameraView.getHolder().getSurface());
        mediaRecorder.setOrientationHint(90);
        // Step 2: Set sources
        mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
        mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        //设置视频输出的格式和编码
        mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);

        // 设置录制文件质量，格式，分辨率之类，这个全部包括了  (30S)
//        mediarecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_480P));  //7.43M  10frame
//        mediarecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_1080P));   //70.94M  10frame
//        mediarecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_CIF));  // 2.6M  5frame/10frame
//        mediarecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_QCIF));  //0.76M   30frame  模糊
//        mediarecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_QVGA));  //2.1M
//        mediarecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_TIME_LAPSE_CIF));  //不支持
//        mediarecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_LOW));  //766KB  还行  比QUALITY_QCIF好
//        mediarecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_TIME_LAPSE_LOW));  //1M 质量类似LOW
//        mediarecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_TIME_LAPSE_480P));  //480p效果
//        mediarecorder.setAudioEncoder(MediaRecorder.AudioEncoder.);
//        mediarecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);

        CamcorderProfile camcorderProfile = null;
//        if (CamcorderProfile.hasProfile(CamcorderProfile.QUALITY_1080P)){
//            camcorderProfile = CamcorderProfile.get(CamcorderProfile.QUALITY_1080P);
//        }
////        else
//        if (CamcorderProfile.hasProfile(CamcorderProfile.QUALITY_720P)) {
//            camcorderProfile = CamcorderProfile.get(CamcorderProfile.QUALITY_720P);
//        }
//        else
        if (CamcorderProfile.hasProfile(CamcorderProfile.QUALITY_480P)) {
            camcorderProfile = CamcorderProfile.get(CamcorderProfile.QUALITY_480P);
        }
//        CamcorderProfile camcorderProfile = CamcorderProfile.get(CamcorderProfile.QUALITY_480P);
        //after setVideoSource(),after setOutFormat()
        //............默认了..........下面的
//        mediaRecorder.setVideoSize(camcorderProfile.videoFrameWidth, camcorderProfile.videoFrameHeight);
        mediaRecorder.setVideoSize(640, 480);
        mediaRecorder.setAudioEncodingBitRate(44100);
        Log.d("Ani", camcorderProfile.videoBitRate + " : " + (2 * 1024 * 1024));
        if (camcorderProfile.videoBitRate > 5 * 1024 * 1024)
            mediaRecorder.setVideoEncodingBitRate(5 * 1024 * 1024);
        else
            mediaRecorder.setVideoEncodingBitRate(camcorderProfile.videoBitRate);

        //设置编码比特率,不设置会使视频图像模糊
//        mediarecorder.setVideoEncodingBitRate(5*1024*1024);  //清晰     512*1024(不清楚)
//        mediarecorder.setVideoEncodingBitRate(900*1024); //较为清晰，且文件大小为3.26M(30秒)
//        mediarecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);  //H263的貌似有点不清晰

        //after setVideoSource(),after setOutFormat();
        mediaRecorder.setVideoFrameRate(camcorderProfile.videoFrameRate);
        //after setOutputFormat()
        mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
        //after setOutputFormat()
        mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
        // Step 3: Set output file

        mediaRecorder.setOutputFile(videoPath);
        // Step 4: start and return

        try {
            mediaRecorder.prepare();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return this;
    }

    /**
     * 开始录制
     */
    public boolean startMedia() {
        if (mediaRecorder == null)
            return false;
        mediaRecorder.start();
        return true;
    }

    /**
     * 停止录制
     */
    public void stopMedia(Activity activity) {
        if (mediaRecorder != null) {
            try {
                //下面三个参数必须加，不加的话会奔溃，在mediarecorder.stop();
                //报错为：RuntimeException:stop failed
                mediaRecorder.setOnErrorListener(null);
                mediaRecorder.setOnInfoListener(null);
                mediaRecorder.setPreviewDisplay(null);
                mediaRecorder.stop();
            } catch (Exception e) {
                File file = new File(mVideoPath);
                if (file.exists()) {
                    file.delete();
                }
                Log.d("Ani", "视频过短");
                Toast.makeText(activity, "视频过短", Toast.LENGTH_SHORT).show();
                Log.i("Exception", Log.getStackTraceString(e));
            } finally {
                mediaRecorder.reset();
                if (mCamera != null)
                    mCamera.lock();
                mediaRecorder = null;// 重录解决崩溃需要
            }
        }

    }
}
